package com.fmsz.physicalheadline.fragments.news;

import android.databinding.DataBindingUtil;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.util.Pair;
import android.support.v4.view.ViewCompat;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.fmsz.physicalheadline.BR;
import com.fmsz.physicalheadline.R;
import com.fmsz.physicalheadline.adapter.news.RecycleAdapter;
import com.fmsz.physicalheadline.application.MyApplication;
import com.fmsz.physicalheadline.databinding.FragmentNewsBaseBinding;

import com.fmsz.physicalheadline.databinding.RefreshHeaderBinding;
import com.fmsz.physicalheadline.entity.news.BannersEntity;
import com.fmsz.physicalheadline.entity.news.ContestEntity;
import com.fmsz.physicalheadline.entity.news.DaoMaster;
import com.fmsz.physicalheadline.entity.news.DaoSession;
import com.fmsz.physicalheadline.entity.news.NewsBannersDao;
import com.fmsz.physicalheadline.entity.news.NewsContents;
import com.fmsz.physicalheadline.entity.news.NewsHomeEntity;
import com.fmsz.physicalheadline.entity.news.NewsTop;
import com.fmsz.physicalheadline.interfaces.HttpService;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import in.srain.cube.views.ptr.PtrDefaultHandler;
import in.srain.cube.views.ptr.PtrFrameLayout;
import in.srain.cube.views.ptr.PtrHandler;
import in.srain.cube.views.ptr.PtrUIHandler;
import in.srain.cube.views.ptr.indicator.PtrIndicator;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * A simple {@link Fragment} subclass.
 */
public class NewsBaseFragment extends Fragment implements Callback<NewsHomeEntity>, PtrHandler, PtrUIHandler {

    private int channel_id;
    private  FragmentNewsBaseBinding bind;
    private RecycleAdapter<Object> adapter;
    private int hasBanners;
    private RefreshHeaderBinding header_bind;
    private View header;
    private boolean isLoading;
    private String start_id;
    private boolean REFRESH_ENABLE = true;
    private boolean isRefreshing;
    private HttpService httpService;
    private DaoMaster.DevOpenHelper devOpenHelper;
    private DaoMaster master;
    private DaoSession session;
    private NewsBannersDao newsBannersDao;
    public static final String DB_NAME = "sportHead_db";

    public static NewsBaseFragment newInstance(int channel_id) {
        Bundle args = new Bundle();
        args.putInt("channel_id",channel_id);
        NewsBaseFragment fragment = new NewsBaseFragment();
        fragment.setArguments(args);
        return fragment;
    }

    public NewsBaseFragment() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle bundle = getArguments();
        channel_id = bundle.getInt("channel_id");
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = DataBindingUtil.inflate(LayoutInflater.from(getContext()), R.layout.fragment_news_base, container, false).getRoot();
        bind = DataBindingUtil.bind(view);
        header = DataBindingUtil.inflate(inflater, R.layout.refresh_header,container,false).getRoot();
        header_bind = DataBindingUtil.bind(header);
        bind.ptr.disableWhenHorizontalMove(true);
        bind.ptr.setHeaderView(header);
        bind.ptr.setPtrHandler(this);
        bind.ptr.addPtrUIHandler(this);
        init();

        initDB();
        return view;
    }

    private void initDB() {
        devOpenHelper = new DaoMaster.DevOpenHelper(getContext(), DB_NAME, null);
        master = new DaoMaster(devOpenHelper.getWritableDb());
        session = master.newSession();
        newsBannersDao = session.getNewsBannersDao();
    }

    private void init() {
        HashMap<Class<?>,Pair<Integer,Integer>> map = new HashMap<>();
        map.put(BannersEntity.class,Pair.create(R.layout.news_pager_header, BR.images));
        map.put(NewsTop.class,Pair.create(R.layout.news_top_normal,BR.news_top));
        map.put(NewsContents.class,Pair.create(R.layout.news_normal,BR.news_content));
        map.put(ContestEntity.class,Pair.create(R.layout.news_contest_item,BR.contests));
        adapter = new RecycleAdapter<>(getContext(),new ArrayList<>(),map);
        bind.recycleNews.setAdapter(adapter);
        httpService = ((MyApplication) getActivity().getApplication()).getHttpService();
        httpService.getNewsHome(channel_id,new HashMap<String, String>()).enqueue(this);
        RecyclerView.ItemDecoration decoration = new RecyclerView.ItemDecoration() {
            @Override
            public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
                super.getItemOffsets(outRect, view, parent, state);
                outRect.set(0,0,0,2);
            }

            @Override
            public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) {
                super.onDraw(c, parent, state);
            }

            @Override
            public void onDrawOver(Canvas c, RecyclerView parent, RecyclerView.State state) {
                super.onDrawOver(c, parent, state);
            }
        };
        bind.recycleNews.addItemDecoration(decoration);
        bind.recycleNews.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                View view = bind.recycleNews.getChildAt(bind.recycleNews.getChildCount() - 1);
                int position = bind.recycleNews.getChildAdapterPosition(view);
                if (!isLoading && position>adapter.getItemCount()-5) {
                    Map<String,String> map = new HashMap<>();
                    map.put("start_id",start_id);
                    isLoading = true;
                    httpService.getNewsHome(channel_id,map).enqueue(NewsBaseFragment.this);
                }
            }
        });
    }

    @Override
    public void onResponse(Call<NewsHomeEntity> call, Response<NewsHomeEntity> response) {
        NewsHomeEntity body = response.body();
        if (body.getCode()!=200) {
            return;
        }
        if (isRefreshing) {
            isRefreshing = false;
            adapter.clear();
            bind.ptr.refreshComplete();
        }
        if (!isLoading) {
            BannersEntity bannersEntity = new BannersEntity(body.getData().getBanners());
            ContestEntity contestEntity = new ContestEntity(body.getData().getContest_list());
            if (bannersEntity.getNewsBannerses().size()>0) {
                adapter.add(0, bannersEntity);
                hasBanners = 1;
            }
            if (channel_id==0) {
                adapter.add(hasBanners,contestEntity);
            }
        }
//        long insert = newsBannersDao.insert(response.body().getData().getBanners().get(0));
        isLoading = false;
        start_id = body.getData().getContents().get(body.getData().getContents().size()-1).getId();
        adapter.addAll(body.getData().getTops());
        adapter.addAll(body.getData().getContents());
    }

    @Override
    public void onFailure(Call<NewsHomeEntity> call, Throwable t) {
        if (isRefreshing) {
            isRefreshing = false;
            bind.ptr.refreshComplete();
            writeRefreshTime();
        }
        t.printStackTrace();
        Toast.makeText(getContext(),t.getMessage(), Toast.LENGTH_SHORT).show();
    }

    //记录刷新时间
    private void writeRefreshTime() {
//        Calendar calendar = Calendar.getInstance();
//        SharedPreferences.Editor editor = PREFERENCES.edit();
//        editor.putLong("refresh_time",calendar.getTimeInMillis());
//        editor.commit();
    }

    @Override
    public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
        return PtrDefaultHandler.checkContentCanBePulledDown(frame, content, header);
    }

    @Override
    public void onRefreshBegin(PtrFrameLayout frame) {
        httpService.getNewsHome(channel_id,new HashMap<String, String>()).enqueue(this);
    }


    //刷新时UI的相关操作
    @Override
    public void onUIReset(PtrFrameLayout frame) {
        ViewCompat.setRotation(header_bind.arrow,0);
    }

    @Override
    public void onUIRefreshPrepare(PtrFrameLayout frame) {
        header_bind.refreshTip.setText(getActivity().getText(R.string.pull_to_refresh));
//        PREFERENCES.getLong("refresh_time",Calendar.getInstance().getTimeInMillis());
        header_bind.refreshTime.setText(getActivity().getText(R.string.refresh_time));
    }

    @Override
    public void onUIRefreshBegin(PtrFrameLayout frame) {
        isRefreshing = true;
        header_bind.progress.setVisibility(View.VISIBLE);
        header_bind.arrow.setVisibility(View.GONE);
        header_bind.refreshTip.setText(getActivity().getText(R.string.refreshing));
        ViewCompat.animate(header_bind.progress)
                .rotationBy(36000)
                .setDuration(30000)
                .start();
    }

    @Override
    public void onUIRefreshComplete(PtrFrameLayout frame) {
        header_bind.progress.setVisibility(View.GONE);
        header_bind.arrow.setVisibility(View.VISIBLE);
        REFRESH_ENABLE = true;
    }

    @Override
    public void onUIPositionChange(PtrFrameLayout frame, boolean isUnderTouch, byte status, PtrIndicator ptrIndicator) {
        int currentPosY = ptrIndicator.getCurrentPosY();
        int offsetToRefresh = frame.getOffsetToRefresh();
        if (!isRefreshing) {
            if (currentPosY > offsetToRefresh && REFRESH_ENABLE) {
                REFRESH_ENABLE = false;
                ViewCompat.animate(header_bind.arrow)
                        .rotationBy(-180)
                        .setDuration(250)
                        .start();
                header_bind.refreshTip.setText(getActivity().getText(R.string.relese_refresh_data));
            } else if (currentPosY < offsetToRefresh && !REFRESH_ENABLE) {
                REFRESH_ENABLE = true;
                ViewCompat.animate(header_bind.arrow)
                        .rotationBy(180)
                        .setDuration(250)
                        .start();
                header_bind.refreshTip.setText(getActivity().getText(R.string.pull_to_refresh));
            }
        }
    }
}
